<?php
declare (strict_types = 1);

namespace app\middleware;

use app\lib\response\JSON;
use app\model\Operation;
use app\model\User;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Config;

class RequestLog
{
    /**
     * 操作记录中间件
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $requestTime = millisecond();
        $response = $next($request);

        if($request->isPost() || $request->isPut() || $request->isDelete()){
            $operation = new Operation();
            $operation->request_time = ftime();
            $operation->method = $request->method();
            $operation->request_ip = $request->ip();
            $operation->params = json_encode($request->all(),JSON_UNESCAPED_UNICODE);
            $operation->username = $request->session['username'];
            $operation->path = $request->rule()->getRule();
            $operation->cost_time = millisecond()-$requestTime;
            $operation->http_code = 200;
            $operation->save();
        }


        return $response;
    }
}
